//
//  JSBridgeHandler.m
//  iOS-Learning-Demo
//
//  Created by yuan xiaodong on 2021/9/23.
//  Copyright © 2021 yuan. All rights reserved.
//
#import "JSBridgeHandler.h"

static NSString *const BL_JSBRIDGE_HOST         = @"JSBridge";      //主要服务
static NSString *const BL_JSBRIDGE_NAME         = @"name";          //事件名称
static NSString *const BL_JSBRIDGE_PARAMS       = @"params";        //参数
static NSString *const BL_JSBRIDGE_CALLBACKNAME = @"callbackName";  //回调名称

//业务逻辑
static NSString *const BL_JSBRIDGE_DATEPICKER = @"datePicker"; //日期选择

@implementation JSBridgeHandler

#pragma mark - *********** WKScriptMessageHandler ***********

- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
    //2:接收js数据
    if ([message.name isEqualToString:BL_JSBRIDGE_HOST]) {
        NSDictionary *body = message.body;
        if (![body isKindOfClass:[NSDictionary class]]){
            NSLog(@"【JS】接收到JS数据有问题，%@",body);
            return;
        }
        
        NSString *name = [body stringForKey:BL_JSBRIDGE_NAME];
        NSDictionary *params = [body dictionaryForKey:BL_JSBRIDGE_PARAMS];
        NSString *callbackName =  [body stringForKey:BL_JSBRIDGE_CALLBACKNAME];
        
        NSLog(@"【通知】接收到JS数据");
        NSLog(@"name:%@ ",name);
        NSLog(@"params:%@ ",params);
        NSLog(@"callbackName:%@ ",callbackName);
        
        if ([name isEqualToString:BL_JSBRIDGE_DATEPICKER]){
            [self doDatePicker:params callBackName:callbackName];
        }else{
            [self other:name params:params callBackName:callbackName];
        }
    }
}

- (void)doDatePicker:(NSDictionary *)params callBackName:(NSString *)callBackName{
    if (!callBackName){
        return;
    }
    NSDictionary *dic = @{ @"code": @10, @"msg": @"datePicker接收到数据了" ,@"data":@{@"body":@"123"} };
    NSString *str = [dic yy_modelToJSONString];
    NSString *jsCallBack = [NSString stringWithFormat:@"(%@)(%@);", callBackName, str];
    [self handleFinish:jsCallBack];
}

- (void)other:(NSString *)name params:(NSDictionary *)params callBackName:(NSString *)callBackName{
    if (!callBackName){
        return;
    }
    NSString *msg = [NSString stringWithFormat:@"%@ 接收到数据了",name];
    NSDictionary *dic = @{ @"code": @10, @"msg": msg ,@"data":@{@"body":@"123"} };
    NSString *str = [dic yy_modelToJSONString];
    NSString *jsCallBack = [NSString stringWithFormat:@"(%@)(%@);", callBackName, str];
    [self handleFinish:jsCallBack];
}

- (void)handleFinish:(NSString *)str{
    if (self.handleBlock){
        self.handleBlock(str);
    }
}

@end
